﻿using Scap.Info;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;

namespace Scap.Core
{
    public class DeviceTaskHandlerNotification : DeviceTaskHandler
    {
        public DeviceTaskHandlerNotification(DeviceTaskModel model)
            : base(model)
        {

        }



        public override void Run()
        {
            SendMail();
        }



        private void SendMail()
        {
            try
            {
                if (_model.Device.Status == DeviceStatus.Online)
                    return;

                _logger.Info("{0} | Enviando notificación...", _device.IpAddress);

                ConfigurationHandler cHandler = new ConfigurationHandler();
                ScapEmailConfiguration emailConfig = cHandler.GetEmailConfig();

                MailMessage mail = new MailMessage();
                SmtpClient client = new SmtpClient();
                client.Port = emailConfig.Port;
                client.DeliveryMethod = SmtpDeliveryMethod.Network;
                client.UseDefaultCredentials = false;
                client.Host = emailConfig.Host;
                client.EnableSsl = emailConfig.Ssl;
                client.Credentials = new NetworkCredential(emailConfig.Username, emailConfig.Password);

                cHandler.SetNotificationDestinataryList(mail);
                //mail.To.Add("joalsolutions@gmail.com"); // <-- this one
                mail.From = new MailAddress(emailConfig.Email);
                mail.Subject = "SCAP Notificación";

                StringBuilder sb = new StringBuilder();
                sb.AppendLine(string.Format("Conexión al dispositivo '{0}' con IP: {1} FALLO!", _device.Name, _device.IpAddress));
                sb.AppendLine(_device.StatusMessage);
                mail.Body = sb.ToString();
                client.Send(mail);
                _logger.Info("{0} | Enviando notificación...[OK]", _device.IpAddress);
            }
            catch (Exception ex)
            {
                _logger.Error("{0} | Enviando notificación...[FALLO]: {1}", _device.IpAddress, ex.Message);
            }
        }
    }
}
